package com.zhongge.controller;

import com.zhongge.model.entity.User;
import com.zhongge.service.UserService;
import com.zhongge.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @ClassName UserServlet
 * @Description TODO 用户控制层
 * @Author zhongge
 * @Version 1.0
 */
@WebServlet("/user/*")//无论你请求的是用户下面的那一块，那么我都可以跳到这个控制器里面
public class UserServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();

        if ("/loginPage".equals(pathInfo)) {
            // 跳转到登录页面
            request.getRequestDispatcher("/WEB-INF/jsp/user/login.jsp").forward(request, response);
        } else if ("/registerPage".equals(pathInfo)) {
            // 跳转到注册页面
            request.getRequestDispatcher("/WEB-INF/jsp/user/register.jsp").forward(request, response);
        } else if ("/logout".equals(pathInfo)) {
            // 用户退出登录
            HttpSession session = request.getSession();
            session.invalidate(); // 销毁session
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        } else if ("/profile".equals(pathInfo)) {
            // 查看个人资料
            HttpSession session = request.getSession();
            User loginUser = (User) session.getAttribute("user");
            if (loginUser == null) {
                response.sendRedirect(request.getContextPath() + "/user/loginPage");
                return;
            }

            User user = userService.getUserById(loginUser.getId());
            request.setAttribute("user", user);
            request.getRequestDispatcher("/WEB-INF/jsp/user/profile.jsp").forward(request, response);
        } else {
            // 无效路径，返回404
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String pathInfo = request.getPathInfo();

        if ("/login".equals(pathInfo)) {
            // 处理登录请求
            String username = request.getParameter("username");
            String password = request.getParameter("password");

            User user = userService.login(username, password);
            if (user != null) {
                // 登录成功，将用户信息存入session
                HttpSession session = request.getSession();
                session.setAttribute("user", user);
                response.sendRedirect(request.getContextPath() + "/index.jsp");
            } else {
                // 登录失败
                request.setAttribute("errorMsg", "用户名或密码错误");
                request.getRequestDispatcher("/WEB-INF/jsp/user/login.jsp").forward(request, response);
            }
        } else if ("/register".equals(pathInfo)) {
            // 处理注册请求
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String nickname = request.getParameter("nickname");
            String email = request.getParameter("email");

            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setNickname(nickname);
            user.setEmail(email);

            boolean success = userService.register(user);
            if (success) {
                // 注册成功，跳转到登录页面
                request.setAttribute("msg", "注册成功，请登录");
                request.getRequestDispatcher("/WEB-INF/jsp/user/login.jsp").forward(request, response);
            } else {
                // 注册失败
                request.setAttribute("errorMsg", "注册失败，用户名可能已存在");
                request.setAttribute("user", user); // 回显用户输入
                request.getRequestDispatcher("/WEB-INF/jsp/user/register.jsp").forward(request, response);
            }
        } else if ("/update".equals(pathInfo)) {
            // 处理更新用户信息请求
            HttpSession session = request.getSession();
            User loginUser = (User) session.getAttribute("user");
            if (loginUser == null) {
                response.sendRedirect(request.getContextPath() + "/user/loginPage");
                return;
            }

            String nickname = request.getParameter("nickname");
            String email = request.getParameter("email");

            User user = new User();
            user.setId(loginUser.getId());
            user.setNickname(nickname);
            user.setEmail(email);

            boolean success = userService.updateUser(user);
            if (success) {
                // 更新成功，刷新session中的用户信息
                User updatedUser = userService.getUserById(loginUser.getId());
                session.setAttribute("user", updatedUser);
                request.setAttribute("msg", "个人信息更新成功");
            } else {
                request.setAttribute("errorMsg", "个人信息更新失败");
            }

            request.setAttribute("user", userService.getUserById(loginUser.getId()));
            request.getRequestDispatcher("/WEB-INF/jsp/user/profile.jsp").forward(request, response);
        } else {
            // 无效路径，返回404
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
}
